package com.faith.timefloating.db;


import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.faith.timefloating.model.Feed;
import com.faith.timefloating.myutils.Constants;
import com.faith.timefloating.utils.DummyAlg;


public class TblMsg {
	public static final String TABLE_NAME = "tbl_msg";

	public class Column {
		public static final String ID = "id";
		public static final String DATE = "date";
		public static final String MSG = "msg";
	}
	
	public static void createTable(SQLiteDatabase db) {

		String CREATE_QUOTE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + Column.ID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT," + Column.DATE
				+ " TEXT," + Column.MSG + " TEXT)";
		db.execSQL(CREATE_QUOTE_TABLE);
	}
	
	public static ArrayList<String> getMsg(SQLiteDatabase db,String date) {
		ArrayList<String> msg= new ArrayList<String>();
		DummyAlg da= new DummyAlg(Constants.DIGEST_STRING, Constants.DUMMY_STRING);
		Cursor c = db.query(TABLE_NAME, new String[] {Column.MSG}, Column.DATE+"='"+date+"'", null, null,null, null, null);
		if (c.getCount() > 0) {
			c.moveToFirst();
			try{
				String[] arr= new String[2];
				String _ms;
			do{
				_ms=new String(da.decrypt(c.getString(0)));
				arr = _ms.split("@");
				msg.add(arr[1]);
			}while(c.moveToNext());
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}else{
			Log.e("DB","There is no msg!");
		}
		c.close();
		db.close();
		return msg;
	}
	
	public static void insertMgss(SQLiteDatabase db,ArrayList<Feed> feeds) {
		if(feeds.size()>0){
			int tmp = feeds.size();
			for (int i = 0; i < tmp; i++) {
				Feed feed = feeds.get(i);
				insertMsg(feed,db);
			}
		}
		db.close();
	}
	
	private static void insertMsg(Feed feed, SQLiteDatabase db) {
		Cursor c = db.query(TABLE_NAME, new String[] {Column.ID}, Column.MSG+"='"+feed.getContent()+"'", null, null,null, null, null);
		if(c.getCount()>0){
			Log.e("DB","msg exists");
		}else{
			ContentValues vl = new ContentValues();
			vl.put(TblMsg.Column.DATE, feed.date);
			vl.put(TblMsg.Column.MSG, feed.getContent());
			db.insert(TblMsg.TABLE_NAME, null, vl);
		}
		c.close();
	}
}
